using UnityEngine;

public class ParallaxLayer : MonoBehaviour
{
    [SerializeField] Transform cam;
    [SerializeField, Range(0f, 1f)] float hStrength = 0.5f;
    [SerializeField, Range(0f, 1f)] float vStrength = 0.9f;

    private float spriteWidth = 50;
    private Vector3 initialPos;
    private Transform[] tiles;

    private void Start()
    {
        initialPos = transform.position;

        tiles = new Transform[transform.childCount];
        for (int i = 0; i < tiles.Length; i++)
            tiles[i] = transform.GetChild(i);
    }

    private void LateUpdate()
    {
        Vector3 camOffset = cam.position - initialPos;
        transform.position = new Vector3(
            initialPos.x + camOffset.x * hStrength,
            initialPos.y + camOffset.y * vStrength,
            transform.position.z
        );

        float camLocalX = cam.position.x - transform.position.x;

        foreach (Transform tile in tiles)
        {
            float tileLocalX = tile.localPosition.x;

            if (camLocalX - tileLocalX > spriteWidth)
                tile.localPosition += Vector3.right * spriteWidth * tiles.Length;

            else if (camLocalX - tileLocalX < -spriteWidth)
                tile.localPosition -= Vector3.right * spriteWidth * tiles.Length;
        }
    }
}
